import React, { Component } from "react";
import { connect } from "dva";
import { Button, Spin, message } from "antd";
import BasicInfo from "./components/BasicInfo";
import AddApi from "./components/AddApi";
import Loghub from "./components/Loghub";
import Ads from "./components/Ads";
import DataHub from "./components/DataHub";

@connect(stores => ({
  coldata: stores.user,
  sourceData: stores.adddataSource,
  personDep: stores.personSelectModel
}))
class AddInfo extends Component {
  state = {
    sourceName: "",
    appId: "",
    manager: "",
    department: "",
    departmentName: "",
    managerName: "",
    type: 1,
    sourceVisible: false,
    depVisible: false,
    ApiConfig: [],
    AdsConfig: [],
    LogHubConfig: [],
    DataHubConfig: [],
    AllControl: false,
    dsId: "",
    loadingEdit: false,
    through: false,
    editable: true,
    manisible: false
  };

  componentDidMount() {
    this.setState({ loadingEdit: true });
    setTimeout(() => {
      const { key } = this.props.sourceData;
      const {
        coldata: {
          userInfo: {
            userId = "",
            userName = "",
            department = "",
            departmentName = ""
          } = {}
        } = {}
      } = this.props;
      if (key.operate === "add") {
        this.setState({
          type: 1,
          sourceName: "",
          appId: "",
          manager: userId,
          managerName: userName,
          department,
          departmentName
        });
      }
      if (key.operate === "mod") {
        this.setState({ dsId: key.dsId });
        const { dataDetail = {} } = this.props.sourceData;
        this.setState({
          type: dataDetail.dsType,
          sourceName: dataDetail.dsName,
          appId: dataDetail.appId || "",
          manager:
            dataDetail.owner && JSON.parse(dataDetail.owner).length > 0
              ? JSON.parse(dataDetail.owner)[0].key
              : "",
          managerName:
            dataDetail.owner && JSON.parse(dataDetail.owner).length > 0
              ? JSON.parse(dataDetail.owner)[0].name
              : "",
          department: dataDetail.ownerDept,
          departmentName: dataDetail.ownerDeptName,
          editable: dataDetail.inService ? !dataDetail.inService : true
        });
      }
      this.setState({ loadingEdit: false });
    }, 500);
  }

  source = e => {
    if (e.target.value !== "") {
      this.setState({
        sourceVisible: false
      });
    }
    this.setState({
      sourceName: e.target.value
    });
  };

  app = (value = "") => {
    this.setState({
      appId: value
    });
  };

  manage = (e, desc) => {
    this.setState({
      manager: e ? e[0] : "",
      managerName: desc ? desc[0] : "",
      manisible: false
    });
  };

  depart = (e, departmentName) => {
    if (e && e !== "") {
      this.setState({
        depVisible: false
      });
    }
    this.setState({
      department: e,
      departmentName
    });
  };

  dataType = e => {
    this.setState({
      type: e
    });
  };

  // dateSet = e => {
  //   this.setState({
  //     startTime: e[0].format("YYYY-MM-DD HH:mm:ss"),
  //     endTime: e[1].format("YYYY-MM-DD HH:mm:ss")
  //   });
  // };

  save = typeBtn => {
    const { sourceData } = this.props;
    const { key } = sourceData;
    const { operate = "add" } = key;
    const {
      ApiConfig,
      DataHubConfig,
      LogHubConfig,
      AdsConfig,
      type,
      manager,
      sourceName,
      department,
      appId,
      through,
      departmentName,
      editable,
      managerName
    } = this.state;
    let a = true;
    if (typeBtn === "submit" && !through && editable) {
      message.error("连通测试未通过，不可提交");
      a = false;
    }
    if (sourceName === "") {
      this.setState({
        sourceVisible: true
      });
      a = false;
    }
    if (manager === "") {
      this.setState({
        manisible: true
      });
      a = false;
    }
    if (department === "") {
      this.setState({
        depVisible: true
      });
      a = false;
    }
    if (sourceName.split("").length > 20) {
      a = false;
    }
    if (!a) {
      return false;
    }
    if (type === 1) {
      const temp = {
        apiUrl:
          ApiConfig && ApiConfig.length > 0 && ApiConfig[0].url
            ? ApiConfig[0].url
            : "",
        apiMethod:
          ApiConfig && ApiConfig.length > 0 && ApiConfig[0].method
            ? ApiConfig[0].method
            : "",
        apiHost:
          ApiConfig && ApiConfig.length > 0 && ApiConfig[0].host
            ? ApiConfig[0].host
            : "",
        apiAppSecret:
          ApiConfig && ApiConfig.length > 0 && ApiConfig[0].appSecret
            ? ApiConfig[0].appSecret
            : "",
        apiAppKey:
          ApiConfig && ApiConfig.length > 0 && ApiConfig[0].appKey
            ? ApiConfig[0].appKey
            : "",
        dsName: sourceName,
        appId,
        ownerRequest: [{ key: manager, name: managerName }],
        ownerDept: department,
        ownerDeptName: departmentName,
        dsType: type
      };
      this.submit(operate, temp, typeBtn);
    }
    if (type === 2) {
      const temp = {
        adsTableName:
          AdsConfig && AdsConfig.length > 0 && AdsConfig[0].tbIName
            ? AdsConfig[0].tbIName
            : "",
        dsName: sourceName,
        appId,
        ownerRequest: [{ key: manager, name: managerName }],
        ownerDept: department,
        dsType: type,
        ownerDeptName: departmentName
      };
      this.submit(operate, temp, typeBtn);
    }
    if (type === 3) {
      const temp = {
        datahubEndpoint:
          DataHubConfig && DataHubConfig.length > 0 && DataHubConfig[0].endpoint
            ? DataHubConfig[0].endpoint
            : "",
        datahubAccessKeyId:
          DataHubConfig && DataHubConfig.length > 0 && DataHubConfig[0].keyId
            ? DataHubConfig[0].keyId
            : "",
        datahubProjectName:
          DataHubConfig &&
          DataHubConfig.length > 0 &&
          DataHubConfig[0].projectName
            ? DataHubConfig[0].projectName
            : "",
        datahubTopicName:
          DataHubConfig &&
          DataHubConfig.length > 0 &&
          DataHubConfig[0].topicName
            ? DataHubConfig[0].topicName
            : "",
        datahubSubId:
          DataHubConfig && DataHubConfig.length > 0 && DataHubConfig[0].subId
            ? DataHubConfig[0].subId
            : "",
        datahubAccessKeySecret:
          DataHubConfig &&
          DataHubConfig.length > 0 &&
          DataHubConfig[0].accessKey
            ? DataHubConfig[0].accessKey
            : "",
        dsName: sourceName,
        appId,
        ownerRequest: [{ key: manager, name: managerName }],
        ownerDept: department,
        dsType: type,
        ownerDeptName: departmentName
      };
      this.submit(operate, temp, typeBtn);
    }
    if (type === 4) {
      const temp = {
        loghubConsumerGroup:
          LogHubConfig &&
          LogHubConfig.length > 0 &&
          LogHubConfig[0].consumerGroup
            ? LogHubConfig[0].consumerGroup
            : "",
        loghubConsumerName:
          LogHubConfig &&
          LogHubConfig.length > 0 &&
          LogHubConfig[0].consumerName
            ? LogHubConfig[0].consumerName
            : "",
        loghubEndpoint:
          LogHubConfig && LogHubConfig.length > 0 && LogHubConfig[0].endpoint
            ? LogHubConfig[0].endpoint
            : "",
        loghubAccessKeyId:
          LogHubConfig && LogHubConfig.length > 0 && LogHubConfig[0].keyId
            ? LogHubConfig[0].keyId
            : "",
        loghubAccessKeySecret:
          LogHubConfig && LogHubConfig.length > 0 && LogHubConfig[0].keySecre
            ? LogHubConfig[0].keySecre
            : "",
        loghubProjectName:
          LogHubConfig && LogHubConfig.length > 0 && LogHubConfig[0].projectName
            ? LogHubConfig[0].projectName
            : "",
        loghubLogStore:
          LogHubConfig && LogHubConfig.length > 0 && LogHubConfig[0].logstore
            ? LogHubConfig[0].logstore
            : "",
        dsName: sourceName,
        appId,
        ownerRequest: [{ key: manager, name: managerName }],
        ownerDept: department,
        dsType: type,
        ownerDeptName: departmentName
      };
      this.submit(operate, temp, typeBtn);
    }
    return true;
  };

  submit = (operate, temp, typeBtn) => {
    const { dispatch, history } = this.props;
    if (operate === "add") {
      dispatch({
        type:
          typeBtn !== "submit"
            ? "adddataSource/addDataSource"
            : "adddataSource/editData",
        payload: { ...temp, dsId: "" }
      }).then(() => {
        const { errCode, errMsg, errCodeMod } = this.props.sourceData;
        if (errCode === 0 || errCodeMod === 0) {
          message.success(errCode === 0 ? "保存成功" : "提交成功");
          history.push("/intellPush/recommendCenter/dataSource");
        } else {
          message.error(errMsg);
        }
      });
    } else {
      const { dsId } = this.state;
      dispatch({
        type:
          typeBtn !== "submit"
            ? "adddataSource/addDataSource"
            : "adddataSource/editData",
        payload: { ...temp, dsId }
      }).then(() => {
        const { errCode, errMsg, errCodeMod } = this.props.sourceData;
        if (errCode === 0 || errCodeMod === 0) {
          message.success(errCode === 0 ? "保存成功" : "提交成功");
          history.push("/intellPush/recommendCenter/dataSource");
        } else {
          message.error(errMsg);
        }
      });
    }
  };

  getValue = (e, AllControl, through) => {
    if (this.state.type === 1) {
      this.setState({
        ApiConfig: e,
        AllControl,
        through
      });
    }
    if (this.state.type === 3) {
      this.setState({
        DataHubConfig: e,
        AllControl,
        through
      });
    }
    if (this.state.type === 4) {
      this.setState({
        LogHubConfig: e,
        AllControl,
        through
      });
    }
    if (this.state.type === 2) {
      this.setState({
        AdsConfig: e,
        AllControl,
        through
      });
    }
  };

  render() {
    const { coldata } = this.props;
    const { collapsed } = coldata;
    const {
      type,
      sourceName,
      appId,
      manager,
      managerName,
      department,
      departmentName,
      editable,
      manisible
    } = this.state;
    const tmp = {
      type,
      sourceName,
      appId,
      manager,
      managerName,
      department,
      departmentName
    };
    const { sourceData } = this.props;
    const { dataDetail = {}, key } = sourceData;
    const { operate = "add" } = key;
    const param = [this.state.sourceName, this.state.department];
    return (
      <div>
        <div>
          <Spin spinning={this.state.loadingEdit}>
            <BasicInfo
              source={this.source}
              app={this.app}
              manage={this.manage}
              depart={this.depart}
              dataType={this.dataType}
              dateSet={this.dateSet}
              sourceVisible={this.state.sourceVisible}
              depVisible={this.state.depVisible}
              dataDetail={dataDetail}
              tmp={tmp}
              operate={operate}
              editable={editable}
              manisible={manisible}
            />
          </Spin>
        </div>
        <Spin spinning={this.state.loadingEdit}>
          {this.state.type === 1 ? (
            <AddApi
              getValue={this.getValue}
              dataDetail={dataDetail}
              operate={operate}
              param={param}
              editable={editable}
            />
          ) : null}
          {this.state.type === 3 ? (
            <DataHub
              getValue={this.getValue}
              dataDetail={dataDetail}
              operate={operate}
              param={param}
              editable={editable}
            />
          ) : null}
          {this.state.type === 4 ? (
            <Loghub
              getValue={this.getValue}
              dataDetail={dataDetail}
              operate={operate}
              param={param}
              editable={editable}
            />
          ) : null}
          {this.state.type === 2 ? (
            <Ads
              getValue={this.getValue}
              dataDetail={dataDetail}
              operate={operate}
              param={param}
              editable={editable}
            />
          ) : null}
        </Spin>
        <div
          style={{
            position: "fixed",
            backgroundColor: "#fff",
            bottom: 0,
            // marginRight: 24,
            marginLeft: -16,
            width: collapsed ? "calc(100% - 66px)" : "calc(100% - 202px)",
            display: "flex",
            justifyContent: "flex-end",
            height: 64,
            alignItems: "center",
            boxShadow: "0px -1px 2px 0px rgba(0, 0, 0, 0.03)",
            borderTop: "1px solid #e8e8e8"
          }}
        >
          <Button
            onClick={() => {
              this.props.history.push("/intellPush/recommendCenter/dataSource");
            }}
          >
            取消
          </Button>
          <Button
            style={{ marginLeft: 8, marginRight: 8 }}
            onClick={() => this.save("save")}
            disabled={
              operate === "mod" &&
              dataDetail.useStatus &&
              dataDetail.useStatus === 1
            }
          >
            保存
          </Button>
          <Button
            type="primary"
            style={{ marginRight: 16 }}
            onClick={() => this.save("submit")}
          >
            提交
          </Button>
        </div>
      </div>
    );
  }
}

export default AddInfo;
